package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type getDirectoryContentsResponse struct {
	FolderId model.SnowflakeIdType `form:"folderId" binding:"required"`
}

func (UserFileModuleApi) GetDirectoryContents(c *gin.Context) {
	var req getDirectoryContentsResponse
	if err := c.ShouldBindQuery(&req); err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	var files []model.FileModel

	// 构建查询条件
	query := global.DB.Where("file_pid = ? AND user_id = ? AND del_flag = ?", req.FolderId, userId, enums.Normal).
		Order("is_folder desc, created_at desc")
	if err := query.Find(&files).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.OkWithData([]model.FileModel{}, c)
			return
		}
		logrus.Errorf("GetDirectoryContents error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	res.OkWithData(files, c)
}
